"""
处理标记的图片
"""
import os
import xml.etree.ElementTree as ET


class XmlProcess:
    def __init__(self, path):
        """

        :param path: 要处理的xml文件路径
        """
        self.xml_path = path

    def process_xml(self):
        """
        处理xml文件
        :return:
        """
        for filename in os.listdir(self.xml_path):
            # 1. 获取当前文件的对象
            et = ET.parse(os.path.join(self.xml_path, filename))

            # 2. 获取当前文件的根
            root = et.getroot()

            # 3. 获取当前文件的size
            size = root.find('size')
            img_width = float(size.find("width").text)  # 加上.text才能显示其大小
            # print(type(img_width))  # <class 'str'>
            img_height = float(size.find("height").text)
            img_depth = float(size.find("depth").text)
            # print(img_height)
            # print(img_depth)

            # 4. 获取当前文件的每个图片的位置，并做归一化处理
            for xml_object in root.findall("object"):
                # # 将图片的位置进行归一化方法一
                # for elem in xml_object.iter("bndbox"):
                #     print(elem.find("xmin").text)
                #     print(elem.find("ymin").text)
                #     ...
                # 将图片进行归一化处理方法二
                xmin = float(xml_object.find("bndbox").find("xmin").text) / img_width
                ymin = float(xml_object.find("bndbox").find("ymin").text) / img_height
                xmax = float(xml_object.find("bndbox").find("xmax").text) / img_width
                ymax = float(xml_object.find("bndbox").find("ymax").text) / img_height
                print(xmin, ymin, xmax, ymax)
        pass


if __name__ == '__main__':
    xp = XmlProcess(r"F:\virtual_environment\AI_Study\AI_study_code\人工智能物体检测和分割"
                    r"\YOLO与SSD\datasets\commodity\Annotations/")

    xp.process_xml()
